<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Radio extends MY_Controller{

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/home
	 *	- or -  
	 * 		http://example.com/index.php/home/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
    function __construct()
    {
        parent::__construct();
		//Google Analytics ID
		$this->data['ga_id'] = 5;		
				
		//Load Fashion Script
		$this->data['js'][] = "playlistScript.js";
		$this->data['css'][] = "playlistStyle.css";
		
		//Configuration
		$this->member_limit = 50;
		$this->guest_limit = 20;
		
		//alias Condition
		if($this->uri->segment(1)!="" && !preg_match('/home|category|you2play|member|cover_page|music|video|ajax_.+?$/',$this->uri->segment(1))):
			$this->index($this->uri->segment(1));
			exit;
		endif;
    }	
	
	/*Check Activity Time*/
	private function is_activity_time()
	{
		//Load Library
		$this->load->library('redis');
				
		$dataPlaylistActivityStart = convertDatetime($this->redis->get('dataPlaylistActivityStart'));
		$dataPlaylistActivityEnd = convertDatetime($this->redis->get('dataPlaylistActivityEnd'));
		if(strtotime($dataPlaylistActivityStart) < time() && time() < strtotime($dataPlaylistActivityEnd)):
			return true;
		else:
			return false;
		endif;	
	}

	/*Playlist*/	 
	public function index()
	{
		//Load Javascript
		$this->data['js'][] = "jquery.multipleelements.cycle.min.js";
		$this->data['js'][] = "jquery.waterwheelCarousel.min.js";
		
		//Load Top Sub Menu
		$this->data['top_sub_menu'] = $this->load->view($this->router->class."/top_sub_menu",'', TRUE);		

		//Playlist Hilight
		$this->data['dataPlaylistHilight'] = $this->db
		->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
		->order_by('t.playlist_id','DESC')
		->get_where('playlist as t',array('t.is_publish' => '1','t.is_hilight' => '1'),5)
		->result();
		
		//Playlist New
		$this->data['dataPlaylistNew'] = $this->db
		->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
		->order_by('t.playlist_id','DESC')
		->get_where('playlist as t',array('t.is_publish' => '1'),6)
		->result();
		
		//Playlist Hit (Views)
		$this->data['dataPlaylistRecommend'] = $this->db
		->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
		->order_by('t.playlist_id','DESC')
		->get_where('playlist as t',array('t.is_publish' => '1','t.is_recommend' => '1'),6)
		->result();
		
		//Playlist Hot (Views)
		$this->data['dataPlaylistHit'] = $this->db
		->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
		->order_by('t.views','DESC')
		->get_where('playlist as t',array('t.is_publish' => '1'),6)
		->result();				
				
		$this->data['content'] = $this->router->class."/".$this->router->method;
		$this->load->view("templates/".$this->folder_templates."templates", $this->data);	
	}
	
	/*Playlist Category*/
	public function category($mode = NULL)
	{
		if(empty($mode)) $this->page_missing();

		//Load Javascript
		$this->data['js'][] = "jquery.multipleelements.cycle.min.js";
						
		//Load Library
  		$this->load->library('pagination');	
		
		//Load Top Sub Menu
		$this->data['top_sub_menu'] = $this->load->view($this->router->class."/top_sub_menu",'', TRUE);					
				
		//Playlist Category
		$this->data['dataCategory'] = $this->ajax_playlist_pager($mode);
		
		$this->data['content'] = $this->router->class."/".$this->router->method;
		$this->load->view("templates/".$this->folder_templates."templates", $this->data);				
	}
	
	private function ajax_playlist_pager($mode,$ajax = FALSE)
	{
		switch($mode):
			case 'new':
				$this->data['category_title'] = 'สถานีใหม่';
				$per_page = 12;
				$searchCondition = "t.is_publish = '1'";
				$order_by = "t.playlist_id DESC";
			break;
			case 'recommend':
				$this->data['category_title'] = 'สถานีแนะนำ';
				$per_page = 12;
				$searchCondition = "t.is_publish = '1' AND t.is_recommend = '1'";
				$order_by = "t.playlist_id DESC";			
			break;
			case 'hit':
				$this->data['category_title'] = 'สถานียอดนิยม';
				$per_page = 12;
				$searchCondition = "t.is_publish = '1'";
				$order_by = "t.views DESC";			
			break;
			case 'you2play':
				$this->data['category_title'] = 'สถานียูทูเพลย์';
				$per_page = 12;
				$searchCondition = "t.is_publish = '1' AND t.member_id IS NULL";
				$order_by = "t.views DESC";			
			break;
			case 'member':
				$this->data['category_title'] = 'สถานีสมาชิกยูทูเพลย์';
				$per_page = 12;
				$searchCondition = "t.is_publish = '1' AND t.member_id IS NOT NULL AND j.playlist_song != ''";
				$order_by = "t.views DESC";			
			break;					
			default:
				$this->page_missing();
		endswitch;
					
		/*Pager*/		
		$config['base_url'] = current_url().'?'.query_string(array('p'));
		$config['total_rows'] = $this->db->from('playlist as t')
		->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
		->where($searchCondition)	
		->count_all_results();
		$config['per_page'] = $per_page;
		$config['num_links'] = 5;
		$config['first_link'] = '&laquo;';
		$config['first_tag_open'] = '<span class="first">';
		$config['first_tag_close'] = '</span>';				
		$config['last_link'] = '&raquo;';
		$config['last_tag_open'] = '<span class="last">';
		$config['last_tag_close'] = '</span>';		
		$config['next_tag_open'] = '<span class="prev">';
		$config['next_tag_close'] = '</span>';	
		$config['prev_tag_open'] = '<span class="next">';
		$config['prev_tag_close'] = '</span>';			
		$config['cur_tag_open'] = '<span class="num_tag current">';
		$config['cur_tag_close'] = '</span>';
		$config['num_tag_open'] = '<span class="num_tag">';
		$config['num_tag_close'] = '</span>';				
		$config['page_query_string'] = TRUE;
		$config['query_string_segment'] = 'p';
		$this->pagination->initialize($config);
		$this->data['pager'] = $this->pagination->create_links();
		
		$this->data['dataPlaylist'] = $this->db
		->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
		->order_by($order_by)			
		->get_where('playlist as t',$searchCondition,$config['per_page'],intval($this->input->get('p')))
		->result();
		
		if($ajax):
			echo $this->load->view($this->router->class."/ajax_playlist_pager", $this->data, TRUE);
			exit;
		else:
			return $this->load->view($this->router->class."/ajax_playlist_pager", $this->data, TRUE);		
		endif;
	}	
	
	public function you2play($alias = NULL)
	{
		$is_exist = $this->db->from('playlist_info')->where(array('playlist_alias' => $alias))->count_all_results();
		if(!empty($is_exist)):
			/*Load Playlist*/
			$this->data['dataPlaylistSelect'] = $this->db
			->join('playlist as j','j.playlist_id=t.playlist_id','INNER')
			->get_where('playlist_info as t',array('t.playlist_alias' => $alias),1)->row();
			$you2play_playlist = $this->data['dataPlaylistSelect']->playlist_song;
			
			/*Update View*/
			$this->update_playlist_view($this->data['dataPlaylistSelect']->playlist_id);				
				
			//Set SEO Tag
			$this->data['seo_title'] = ''.$this->data['dataPlaylistSelect']->playlist_name.' | You2Play.com';
			$this->data['seo_description'] = ($this->data['dataPlaylistSelect']->playlist_brief ? $this->data['dataPlaylistSelect']->playlist_brief:$this->data['seo_description']);
				
			$this->data['module_facebook_plugins_share'] = $this->module_facebook_plugins_share();
			$this->data['fb_title'] = $this->data['seo_title'];
			$this->data['fb_image'] = image_asset_url('../uploads/playlist/images/120x120/'.$this->data['dataPlaylistSelect']->playlist_file_name.'.'.$this->data['dataPlaylistSelect']->playlist_file_ext);
			$this->data['fb_type'] = 'music.playlist';
		else:
			$this->page_missing();
		endif;

		//Load Media Player
		$this->data['js'][] = "media/jwplayer.js";					

		//Load Module
		$this->data['module_facebook_plugins_share'] = $this->module_facebook_plugins_share();
		
		//Load Top Sub Menu
		$this->data['top_sub_menu'] = $this->load->view($this->router->class."/top_sub_menu",'', TRUE);		
		
		$this->data['dataResult'] = "";
		if(!empty($you2play_playlist)):
			$content_arr = array();
			$content_id_arr = explode(':',$you2play_playlist);
			foreach($content_id_arr as $value):
				
				if(preg_match('/video_/',$value)): //if it's video
					$value = preg_replace('/video_/','',$value);
					$dataResult = $this->db->select('t.video_id as content_id,t.is_relate_song,t.create_date,j.video_name as song_name,j.is_youtube,j.video_embed,j.video_file_name as song_file_name,j.video_file_ext as song_file_ext,j.video_thumb_name as album_file_name,j.video_thumb_ext as album_file_ext')
					->join('video_info as j','j.video_id=t.video_id','INNER')
					->get_where('video as t',array('t.video_id' => intval($value)))
					->row();
					if($dataResult->is_relate_song == '1'):
						$dataResult->artist = $this->db->select('k.artist_name')
						->join('song_artist as j','j.song_id=t.song_id','INNER')
						->join('artist_info as k','k.artist_id=j.artist_id','INNER')
						->get_where('video_song as t',array('t.video_id' => $dataResult->content_id,'j.is_default' => '1'))
						->result();							
					else:
						$dataResult->artist = $this->db->select('j.artist_name')
						->join('artist_info as j','j.artist_id=t.artist_id','INNER')
						->get_where('video_artist as t',array('t.video_id' => $dataResult->content_id))
						->result();							
					endif;				
					//Youtube
					if($dataResult->is_youtube == '1'):
						preg_match('/embed\/(.+?)[^a-zA-Z0-9-_]/',$dataResult->video_embed,$matches);
						if(!empty($matches[1])) $dataResult->youtube_link = "http://www.youtube.com/watch?v=".$matches[1];
					endif;
					$dataResult->content_url = $this->data['video_url'].'play/'.$dataResult->content_id.'-'.seo_url($dataResult->song_name);
					$dataResult->content_type = 'video';
					$content_arr[] = $dataResult;								
				else:
					$dataResult = $this->db->select('t.song_id as content_id,t.create_date,j.song_name,j.is_youtube,j.song_embed,j.song_file_name,j.song_file_ext,l.album_file_name,l.album_file_ext')
					->join('song_info as j','j.song_id=t.song_id','INNER')
					->join('song_album as k','k.song_id=t.song_id','INNER')
					->join('album_info as l','l.album_id=k.album_id','INNER')
					->get_where('song as t',array('t.song_id' => intval($value),'k.is_default' => '1'),1)
					->row();
					$dataResult->artist = $this->db->select('j.artist_name')
					->join('artist_info as j','j.artist_id=t.artist_id','INNER')
					->get_where('song_artist as t',array('t.song_id' => $dataResult->content_id,'t.is_default' => '1'))
					->result();
					//Youtube
					if($dataResult->is_youtube == '1'):
						preg_match('/embed\/(.+?)[^a-zA-Z0-9-_]/',$dataResult->song_embed,$matches);
						if(!empty($matches[1])) $dataResult->youtube_link = "http://www.youtube.com/watch?v=".$matches[1];
					endif;
					$dataResult->content_url = $this->data['music_url'].'play/'.$dataResult->content_id.'-'.seo_url($dataResult->song_name);
					$dataResult->content_type = 'song';
					$content_arr[] = $dataResult;				
				endif;
			endforeach;
			$this->data['dataResult'] = $content_arr;
		endif;
		
		//GA Events
		$this->data['ga_event'] = 'CI-'.'playlist_you2play';
		$this->data['content'] = $this->router->class."/play";
		
		$this->load->view("templates/".$this->folder_templates."templates", $this->data);			
	}
	
	public function member($alias = NULL)
	{	
		if(!empty($alias)): //alias playlist
			//Check Alias is Exist
			$is_exist = $this->db->from('playlist as t')
			->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
			->where("j.playlist_alias = '".$alias."' AND t.member_id IS NOT NULL AND t.is_publish = '1'")
			->count_all_results();
			if(empty($is_exist) || !empty($this->data['member'])): //No playlist
				if(!empty($this->data['member'])): //Create new playlist
					$is_exist = $this->db->from('playlist')
					->where(array('member_id' => $this->data['member']['member_id']))
					->count_all_results();
					if(empty($is_exist)):
						$datetime = date('Y-m-d H:i:s');
						$dataMember = $this->db->select('t.member_id,t.fb_id,j.username')
						->join('member_info as j','j.member_id=t.member_id','INNER')
						->get_where('member as t',array('t.member_id' => $this->data['member']['member_id']),1)
						->row();
						$data = array(
							'member_id' => $dataMember->member_id,
							'is_publish' => '0',
							'update_by' => $dataMember->username,
							'create_date' => $datetime,
							'update_date' => $datetime,
						);
						$this->db->insert('playlist',$data);
						$playlist_id = $this->db->insert_id();
						$data = array(
							'playlist_id' => $playlist_id,
							'playlist_alias' => $dataMember->fb_id,
							'playlist_name' => $dataMember->username,
							'playlist_file_name' => 'mylist_01',
							'playlist_file_ext' => 'jpg',
						);
						$this->db->insert('playlist_info',$data);						
					endif;
				else:
					$this->page_missing();
				endif;				
			endif;

			/*Load Playlist*/
			$this->data['dataPlaylistSelect'] = $this->db->select('k.username,j.*,t.*')
			->join('playlist as j','j.playlist_id=t.playlist_id','INNER')
			->join('member_info as k','k.member_id=j.member_id','INNER')
			->get_where('playlist_info as t',array('t.playlist_alias' => $alias),1)->row();
			$you2play_playlist = $this->data['dataPlaylistSelect']->playlist_song;
			
			/*Update View*/
			$this->update_playlist_view($this->data['dataPlaylistSelect']->playlist_id);			
				
			//Set SEO Tag
			$this->data['seo_title'] = ''.$this->data['dataPlaylistSelect']->playlist_name.' | You2Play.com';
			$this->data['seo_description'] = ($this->data['dataPlaylistSelect']->playlist_brief ? $this->data['dataPlaylistSelect']->playlist_brief:$this->data['seo_description']);
				
			$this->data['module_facebook_plugins_share'] = $this->module_facebook_plugins_share();
			$this->data['fb_title'] = $this->data['seo_title'];
			$this->data['fb_image'] = image_asset_url('playlist/'.$this->data['dataPlaylistSelect']->playlist_file_name.'.'.$this->data['dataPlaylistSelect']->playlist_file_ext);
			$this->data['fb_type'] = 'music.playlist';			
		else: //not alias playlist
			if(!empty($this->data['member'])): //login facebook
				$dataMember = $this->db->select('t.member_id,t.fb_id,j.username')
				->join('member_info as j','j.member_id=t.member_id','INNER')
				->get_where('member as t',array('t.member_id' => $this->data['member']['member_id']),1)
				->row();	
				redirect('member/'.$dataMember->fb_id);
			else:
				$you2play_playlist = @get_cookie('you2play_playlist');
				//Add Time To Expire
				if(@get_cookie('you2play_playlist')):
					$mycookie = array(
						'name'  => 'you2play_playlist',
						'value' => @get_cookie('you2play_playlist'),
						'expire'=> '259200'
					);
					set_cookie($mycookie);
				endif;			
			endif;
		endif;	
		
		//Load Media Player
		$this->data['js'][] = "media/jwplayer.js";
		
		//Load Jquery UI
		$this->data['js'][] = "jquery-ui-1.9.1.custom.min.js";	
		$this->data['css'][] = "jquery-ui-1.9.1.custom.min.css";
		
		//Load ColorBox
		$this->data['js'][] = "jquery.colorbox-min.js";
		$this->data['css'][] = "colorbox.css";						

		//Load Module
		$this->data['module_facebook_plugins_share'] = $this->module_facebook_plugins_share();
		
		//Load Top Sub Menu
		$this->data['top_sub_menu'] = $this->load->view($this->router->class."/top_sub_menu",'', TRUE);	
		
		$this->data['dataResult'] = "";
		if(!empty($you2play_playlist)):
			$content_arr = array();
			$content_id_arr = explode(':',$you2play_playlist);
			foreach($content_id_arr as $value):
				
				if(preg_match('/video_/',$value)): //if it's video
					$value = preg_replace('/video_/','',$value);
					$dataResult = $this->db->select('t.video_id as content_id,t.is_relate_song,t.create_date,j.video_name as song_name,j.is_youtube,j.video_embed,j.video_file_name as song_file_name,j.video_file_ext as song_file_ext,j.video_thumb_name as album_file_name,j.video_thumb_ext as album_file_ext')
					->join('video_info as j','j.video_id=t.video_id','INNER')
					->get_where('video as t',array('t.video_id' => intval($value)))
					->row();
					if($dataResult->is_relate_song == '1'):
						$dataResult->artist = $this->db->select('k.artist_name')
						->join('song_artist as j','j.song_id=t.song_id','INNER')
						->join('artist_info as k','k.artist_id=j.artist_id','INNER')
						->get_where('video_song as t',array('t.video_id' => $dataResult->content_id,'j.is_default' => '1'))
						->result();							
					else:
						$dataResult->artist = $this->db->select('j.artist_name')
						->join('artist_info as j','j.artist_id=t.artist_id','INNER')
						->get_where('video_artist as t',array('t.video_id' => $dataResult->content_id))
						->result();							
					endif;				
					//Youtube
					if($dataResult->is_youtube == '1'):
						preg_match('/embed\/(.+?)[^a-zA-Z0-9-_]/',$dataResult->video_embed,$matches);
						if(!empty($matches[1])) $dataResult->youtube_link = "http://www.youtube.com/watch?v=".$matches[1];
					endif;
					$dataResult->content_url = $this->data['video_url'].'play/'.$dataResult->content_id.'-'.seo_url($dataResult->song_name);
					$dataResult->content_type = 'video';
					$content_arr[] = $dataResult;					
				else:
					$dataResult = $this->db->select('t.song_id as content_id,t.create_date,j.song_name,j.is_youtube,j.song_embed,j.song_file_name,j.song_file_ext,l.album_file_name,l.album_file_ext')
					->join('song_info as j','j.song_id=t.song_id','INNER')
					->join('song_album as k','k.song_id=t.song_id','INNER')
					->join('album_info as l','l.album_id=k.album_id','INNER')
					->get_where('song as t',array('t.song_id' => intval($value),'k.is_default' => '1'),1)
					->row();
					$dataResult->artist = $this->db->select('j.artist_name')
					->join('artist_info as j','j.artist_id=t.artist_id','INNER')
					->get_where('song_artist as t',array('t.song_id' => $dataResult->content_id,'t.is_default' => '1'))
					->result();
					//Youtube
					if($dataResult->is_youtube == '1'):
						preg_match('/embed\/(.+?)[^a-zA-Z0-9-_]/',$dataResult->song_embed,$matches);
						if(!empty($matches[1])) $dataResult->youtube_link = "http://www.youtube.com/watch?v=".$matches[1];
					endif;
					$dataResult->content_url = $this->data['music_url'].'play/'.$dataResult->content_id.'-'.seo_url($dataResult->song_name);
					$dataResult->content_type = 'song';
					$content_arr[] = $dataResult;				
				endif;
			endforeach;
			$this->data['dataResult'] = $content_arr;
		endif;

		/*Check Activity Time*/
		$this->data['is_activity_time']  = $this->is_activity_time();

		//GA Events
		$this->data['ga_event'] = 'CI-'.'playlist_members';		
		$this->data['content'] = $this->router->class."/play";
		$this->load->view("templates/".$this->folder_templates."templates", $this->data);		
	}
	
	/*Update View*/
	private function update_playlist_view($id)
	{
		//UPDATE Artist (View)
		$this->db->set('views', 'views + 1', FALSE);
		$this->db->where(array('playlist_id' => $id));
		$this->db->update('playlist');
		
		//Keep Stat View
		$datetime = date('Y-m-d');
		$is_exist = $this->db->from('playlist_click_stat')->where(array('playlist_id' => $id,'update_date' => $datetime))->count_all_results();
		if(!empty($is_exist)):
			$this->db->set('playlist_click_views', 'playlist_click_views + 1', FALSE);
			$this->db->where(array('playlist_id' => $id,'update_date' => $datetime));
			$this->db->update('playlist_click_stat');
		else:
			$data = array(
				'playlist_id' => $id,
				'playlist_click_views' => 1,
				'update_date' => $datetime
			);
			$this->db->insert('playlist_click_stat',$data);
		endif;		
	}
	
	public function music($id)
	{
		if(!empty($id)):
			if(!empty($this->data['member'])): //Member
				$dataPlaylist = $this->db->select('t.playlist_id,j.playlist_song')
				->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
				->get_where('playlist as t',array('t.member_id' => $this->data['member']['member_id']),1)
				->row();
				//Limit Items
				if(count(explode(':',$dataPlaylist->playlist_song)) >= $this->member_limit):
					echo "<script>alert('ไม่สามารถเพิ่มเพลส์ลิสได้ เนื่องจากเพลส์ลิสเต็มค่ะ');</script>";
					echo "<script>window.location.href = '".$this->data['playlist_url']."';</script>";
					exit;
				endif;				
				if(!empty($dataPlaylist->playlist_song)):
					$id = $dataPlaylist->playlist_song.':'.$id;
				endif;
				$this->db->update('playlist_info',array('playlist_song' => $id),array('playlist_id' => $dataPlaylist->playlist_id));
			else:
				if(@get_cookie('you2play_playlist')):
					if(count(explode(':',get_cookie('you2play_playlist'))) >= $this->guest_limit):
						echo "<script>alert('ไม่สามารถเพิ่มเพลส์ลิสได้ เนื่องจากเพลส์ลิสเต็มค่ะ');</script>";
						echo "<script>window.location.href = '".$this->data['playlist_url']."';</script>";
						exit;
					else:
						$mycookie = array(
							'name'  => 'you2play_playlist',
							'value' => get_cookie('you2play_playlist').':'.$id,
							'expire'=> '259200'
						);
						set_cookie($mycookie);			
					endif;
				else:
					$mycookie = array(
						'name'  => 'you2play_playlist',
						'value' => $id,
						'expire'=> '259200'
					);
					set_cookie($mycookie);					
				endif;			
			endif;
		endif;
		redirect($this->data['playlist_url'].'member');
		exit;		
	}
	
	public function video($id)
	{
		if(!empty($id)):
			if(!empty($this->data['member'])): //Member
				$dataPlaylist = $this->db->select('t.playlist_id,j.playlist_song')
				->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
				->get_where('playlist as t',array('t.member_id' => $this->data['member']['member_id']),1)
				->row();
				//Limit Items
				if(count(explode(':',$dataPlaylist->playlist_song)) >= $this->member_limit):
					echo "<script>alert('ไม่สามารถเพิ่มเพลส์ลิสได้ เนื่องจากเพลส์ลิสเต็มค่ะ');</script>";
					echo "<script>window.location.href = '".$this->data['playlist_url']."';</script>";
					exit;
				endif;
				if(!empty($dataPlaylist->playlist_song)):
					$id = $dataPlaylist->playlist_song.':video_'.$id;
				endif;
				$this->db->update('playlist_info',array('playlist_song' => $id),array('playlist_id' => $dataPlaylist->playlist_id));
			else:
				if(@get_cookie('you2play_playlist')):
					if(count(explode(':',get_cookie('you2play_playlist'))) >= $this->guest_limit):
						echo "<script>alert('ไม่สามารถเพิ่มเพลส์ลิสได้ เนื่องจากเพลส์ลิสเต็มค่ะ');</script>";
						echo "<script>window.location.href = '".$this->data['playlist_url']."';</script>";
						exit;
					else:
						$mycookie = array(
							'name'  => 'you2play_playlist',
							'value' => get_cookie('you2play_playlist').':'.'video_'.$id,
							'expire'=> '259200'
						);
						set_cookie($mycookie);			
					endif;
				else:
					$mycookie = array(
						'name'  => 'you2play_playlist',
						'value' => 'video_'.$id,
						'expire'=> '259200'
					);
					set_cookie($mycookie);					
				endif;			
			endif;
		endif;
		redirect($this->data['playlist_url'].'member');
		exit;		
	}
	
	/*Remove from playlist*/
	public function ajax_remove_from_playlist()
	{
		$id = $this->input->post('id');
		if(!empty($this->data['member'])): //Member
			$dataPlaylist = $this->db->select('t.playlist_id,j.playlist_song')
			->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
			->get_where('playlist as t',array('t.member_id' => $this->data['member']['member_id']),1)
			->row();
			if(!empty($dataPlaylist->playlist_song)):
				if($id == -1): //Clear All
					$this->db->update('playlist_info',array('playlist_song' => ''),array('playlist_id' => $dataPlaylist->playlist_id));
				else:
					$song_id_arr = explode(':',$dataPlaylist->playlist_song);
					unset($song_id_arr[$id]);
					$this->db->update('playlist_info',array('playlist_song' => implode(':',$song_id_arr)),array('playlist_id' => $dataPlaylist->playlist_id));
				endif;
			endif;
		else:
			if(@get_cookie('you2play_playlist')):
				if($id == -1): //Clear All
					delete_cookie('you2play_playlist');
				else:
					$song_id_arr = explode(':',get_cookie('you2play_playlist'));
					unset($song_id_arr[$id]);
					//$value = preg_replace('/'.$id.'|:'.$id.'/','',get_cookie('you2play_playlist'));
					$mycookie = array(
						'name'  => 'you2play_playlist',
						'value' => implode(':',$song_id_arr),
						'expire'=> '259200'
					);
					set_cookie($mycookie);				
				endif;	
			endif;			
		endif;
		exit;
	}
	
	public function ajax_swap_to_playlist()
	{
		$items = array();
		foreach($_POST as $value):
			$items[] = $value[0];
		endforeach;
		if(!empty($this->data['member'])): //Member
			$dataPlaylist = $this->db->select('t.playlist_id,j.playlist_song')
			->join('playlist_info as j','j.playlist_id=t.playlist_id','INNER')
			->get_where('playlist as t',array('t.member_id' => $this->data['member']['member_id']),1)
			->row();
			$this->db->update('playlist_info',array('playlist_song' => implode(':',$items)),array('playlist_id' => $dataPlaylist->playlist_id));		
		else:
			$mycookie = array(
				'name'  => 'you2play_playlist',
				'value' => implode(':',$items),
				'expire'=> '259200'
			);
			set_cookie($mycookie);		
		endif;
		exit;
	}
	
	public function ajax_update_status()
	{
		$status = $this->input->post('is_publish');
		if(!empty($this->data['member'])):
			$this->db->update('playlist',array('is_publish' => ''.$status.''),array('member_id' => $this->data['member']['member_id']));
		endif;
		exit;
	}
	
	public function ajax_update_playlist()
	{
		$playlist_name = strip_tags(trim($this->input->post('playlist_name')));
		$playlist_img_arr = explode('.',$this->input->post('playlist_img'));
		if(!empty($playlist_name)):
			$this->db->update('playlist_info',array('playlist_name' => ''.$playlist_name.'','playlist_file_name' => $playlist_img_arr[0],'playlist_file_ext' => $playlist_img_arr[1]),array('playlist_alias' => $this->data['member']['fb_id']));
		endif;
		exit;
	}
	
	/*Vote Playlist*/
	public function ajax_vote_playlist()
	{
		$playlist_id = $this->input->post('playlist_id');
		$fb_id = $this->input->post('fb_id');
		$datetime = date('Y-m-d');
		$is_activity_time = $this->is_activity_time();
		$is_exist = $this->db->from('playlist_vote')
		->where("playlist_id = ".$playlist_id." AND fb_id = ".$fb_id." AND update_date = '".$datetime."'")
		->count_all_results();
		if(empty($is_exist) && !empty($playlist_id) && !empty($fb_id)):
			$is_exist = $this->db->from('playlist_vote')
			->where("playlist_id = ".$playlist_id." AND fb_id = ".$fb_id."")
			->count_all_results();
			if(empty($is_exist)): //Create
				$data = array(
					'playlist_id' => $playlist_id,
					'fb_id' => $fb_id,
					'vote' => 1,
					'update_date' => $datetime
				);
				if($is_activity_time) $data['vote_activity'] = 1;
				$this->db->insert('playlist_vote',$data);
			else: //Update			
				$this->db->set('vote', 'vote + 1', FALSE);
				if($is_activity_time) $this->db->set('vote_activity', 'vote_activity + 1', FALSE);
				$this->db->set('update_date', $datetime);
				$this->db->where(array('playlist_id' => $playlist_id,'fb_id' => $fb_id));
				$this->db->update('playlist_vote');				
			endif;
			
			//Vote Main
			$this->db->set('vote', 'vote + 1', FALSE);
			if($is_activity_time) $this->db->set('vote_activity', 'vote_activity + 1', FALSE);
			$this->db->where(array('playlist_id' => $playlist_id));
			$this->db->update('playlist');			
		else:
			echo "คุณได้ให้คะแนนโหวตเพลลิสต์นี้ไปแล้ว คุณสามารถกลับมาโหวตใหม่วันพรุ่งนี้ค่ะ";
		endif;
		exit;
	}
}


/* End of file video.php */
/* Location: ./application/controllers/video.php */